﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ItemQuoteLibrary
{
    public class ItemQuoteDecoderBin : ItemQuoteDecoder
    {
        public Encoding EncodingType { get; private set; }

        public ItemQuoteDecoderBin(string encodingType)
        {
            EncodingType = Encoding.GetEncoding(encodingType);
        }

        public ItemQuoteDecoderBin()
            : this(ItemQuoteBinConst.DEFAULT_CHAR_ENC)
        {
        }

        public ItemQuote Decode(Stream stream)
        {
            BinaryReader src = new BinaryReader(new BufferedStream(stream));

            long itemNumber = IPAddress.NetworkToHostOrder(src.ReadInt64());
            int quantity = IPAddress.NetworkToHostOrder(src.ReadInt32());
            int unitPrice = IPAddress.NetworkToHostOrder(src.ReadInt32());
            byte flags = src.ReadByte();

            int stringLength = src.Read(); 

            if (stringLength == -1)
                throw new EndOfStreamException();

            byte[] stringBuf = new byte[stringLength];
            src.Read(stringBuf, 0, stringLength);
            String itemDesc = EncodingType.GetString(stringBuf);

            return new ItemQuote(itemNumber, itemDesc, quantity, unitPrice,
                ((flags & ItemQuoteBinConst.DISCOUNT_FLAG) == ItemQuoteBinConst.DISCOUNT_FLAG),
                ((flags & ItemQuoteBinConst.IN_STOCK_FLAG) == ItemQuoteBinConst.IN_STOCK_FLAG));
        }


        public ItemQuote Decode(byte[] packet)
        {
            Stream payload = new MemoryStream(packet, 0, packet.Length, false);
            return Decode(payload);
        }

    }
}